package com.eastedu.superise.handler.question.handler.answer;

import com.eastedu.exception.ServiceException;

import java.util.ArrayList;
import java.util.List;
import java.util.Objects;

/**
 * 将答案字符转换为int
 *
 * @author ZhenZhong
 */
public class CompositeAsciiConverter {

    private static final List<AsciiConverter> CONVERTERS = new ArrayList<>();

    static {
        CONVERTERS.add(new DigitalConverter());
        CONVERTERS.add(new ChineseNumeralsConverter());
        CONVERTERS.add(new LowcaseLetterConverter());
        CONVERTERS.add(new UppercaseLetterConverter());
        CONVERTERS.add(new RomanNumeralConverter());
        CONVERTERS.add(new SpecialCharacter1Converter());
        CONVERTERS.add(new SpecialCharacter2Converter());
        CONVERTERS.add(new SpecialCharacter3Converter());
        CONVERTERS.add(new SpecialCharacter4Converter());
    }

    private final AsciiConverter judgementConverter = new SpecialForJudgementConverter();

    private AsciiConverter getConverter(String answerString) {
        for (AsciiConverter converter : CONVERTERS) {
            if (converter.isSupported(answerString)) {
                return converter;
            }
        }
        throw new ServiceException("不支持的答案类型: " + answerString);
    }

    /**
     * 将答案字符串转换为数字
     *
     * @param answerString the answer string
     * @return the int
     * @throws ServiceException the service exception
     */
    public int convert(String answerString) throws ServiceException {
        if (Objects.isNull(answerString)) {
            return 0;
        }
        return this.convert(answerString.trim().toLowerCase(), true);
    }

    /**
     * 将答案字符串转换为数字
     * 增加了 判断题T,F的特殊处理（由于作业自己内部子存储数据时，对着判断题答案做了特殊处理，因此这里需要进行适配处理，否则无法正确转换判断题）
     *
     * @param answerString the answer string
     * @param isJudgement  the is judgement
     * @return int int
     * @throws ServiceException the service exception
     */
    public int convert(String answerString, boolean isJudgement) throws ServiceException {
        if (Objects.isNull(answerString)) {
            return 0;
        }
        String lowerCase = answerString.trim().toLowerCase();
        if (isJudgement && judgementConverter.isSupported(lowerCase)) {
            return judgementConverter.convert(lowerCase);
        }
        return this.getConverter(lowerCase).convert(lowerCase);
    }


}
